import {Injectable} from "@angular/core";
import {
  HttpErrorResponse,
  HttpEvent,
  HttpHandler,
  HttpInterceptor,
  HttpRequest,
  HttpResponse
} from "@angular/common/http";
import {catchError, map, Observable, throwError} from "rxjs";
import {NzMessageService} from "ng-zorro-antd/message";
import {Router} from "@angular/router";

@Injectable()
export class AppInterceptor implements HttpInterceptor {

  constructor(private ms: NzMessageService,
              private router: Router) {
  }

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(req).pipe(
      map(event => {
          if (event instanceof HttpResponse) {
            if (event.body.data) {
              event = event.clone({body: event.body.data})
            } else {
              // 如果是没有登录导致，跳转到登录页
              if (event.body.code == 40003) {
                this.router.navigate(['/login'])
              }
              throw new Error(event.body.message)
            }
          }
          return event
        }
      ),
      catchError((err: HttpErrorResponse) => {
        this.ms.error(err.message)
        return throwError(() => new Error(err.message))
      })
    )
  }

}
